package com.coolweather.android;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

    public class MainActivity extends AppCompatActivity {
        private ArrayAdapter arrayAdapter;
        private List<Province> provinceList;
        private List<City> cityList;
        private List<County> countyList;
        private List<String> datalist = new ArrayList<String>();
        public int provinceId = 0;
        public int cityId = 0;
        public int temp = 0;//0省 1市 2县
        private TextView text;
        private ListView list;
        private Handler mHandler = new Handler();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //初始化
            Connector.getDatabase();
            //生成视图
            list = (ListView) findViewById(R.id.list_province);
            arrayAdapter = new ArrayAdapter<>(com.coolweather.android.MainActivity.this,
                    android.R.layout.simple_list_item_1,
                    datalist);
            list.setAdapter(arrayAdapter);
            text = (TextView) findViewById(R.id.tx_top);
            Button bt = (Button) findViewById(R.id.bt_huitui);
            //回退方法
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (temp == 1) {
                        Log.d("info", "btn1方法");
                        text.setText("当前选择:  ");
                        provinceList = DataSupport.findAll(Province.class);
                        datalist.clear();
                        for (Province province : provinceList) {
                            datalist.add(province.getProvinceName());
                        }
                        arrayAdapter.notifyDataSetChanged();
                        temp = 0;
                    } else if (temp == 2) {
                        Log.d("info", "btn2方法");
                        text.setText("当前选择:  ");
                        cityList = DataSupport.findAll(City.class);
                        datalist.clear();
                        for (City city : cityList) {
                            datalist.add(city.getCityName());
                        }
                        arrayAdapter.notifyDataSetChanged();
                        temp = 1;
                    }
                }
            });
            //生成数据视图
            provinceList = DataSupport.findAll(Province.class);
            Log.d("info", String.valueOf(provinceList.size()));
            if (provinceList.size() > 0) {
                datalist.clear();
                for (Province province : provinceList) {
                    datalist.add(province.getProvinceName());
                }
                arrayAdapter.notifyDataSetChanged();
            } else {
                String address = "http://guolin.tech/api/china";
                queryDataFromServer(address, "province");
            }
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    switch (temp) {
                        case 0:
                            Log.d("info", "item0方法");
                            Province pro1 = provinceList.get(i);
                            provinceId = pro1.getProvinceCode();
                            text.setText("当前选择:   " + pro1.getProvinceName());
                            cityList = DataSupport.where("provinceId=?",
                                    String.valueOf(provinceId)).find(City.class);
                            Log.d("info", "itemo查数据库里" + String.valueOf(cityList.size()));
                            if (cityList.size() > 0) {
                                datalist.clear();
                                for (City city : cityList) {
                                    datalist.add(city.getCityName());
                                }
                                arrayAdapter.notifyDataSetChanged();
                                temp = 1;
                            } else {
                                String address = "http://guolin.tech/api/china/" + provinceId;
                                queryDataFromServer(address, "city");
                            }
                            break;
                        case 1:
                            Log.d("info", "item1方法");
                            City city = cityList.get(i);
                            cityId = city.getCityCode();
                            text.setText("当前选择:   " + city.getCityName());
                            countyList = DataSupport.where("cityId=?",
                                    String.valueOf(cityId)).find(County.class);
                            Log.d("info", "item1查数据库方法" + String.valueOf(countyList.size()));
                            if (countyList.size() > 0) {
                                datalist.clear();
                                for (County county : countyList) {
                                    datalist.add(county.getCountyName());
                                }
                                arrayAdapter.notifyDataSetChanged();
                                temp = 2;
                            } else {
                                String address = "http://guolin.tech/api/china/" + provinceId + "/" + cityId;
                                queryDataFromServer(address, "county");
                            }
                            break;
                        case 2:
                            County county = countyList.get(i);
                            Log.d("info", county.toString());
                            Intent intent = new Intent(com.coolweather.android.MainActivity.this, WeatherActivity.class);
                            intent.putExtra("weatherid", county.getWeatherId());
                            startActivity(intent);
                            com.coolweather.android.MainActivity.this.finish();
                            temp = 0;
                            break;
                        default:
                            break;
                    }
                }
            });
        }

        /**
         * 刷新省份ui办法
         */
        public void freshProUi() {
            provinceList = DataSupport.findAll(Province.class);
            Log.d("info", String.valueOf(provinceList.size()));
            datalist.clear();
            for (Province province : provinceList) {
                datalist.add(province.getProvinceName());
            }
            arrayAdapter.notifyDataSetChanged();
        }

        /**
         * 刷新城市ui办法
         */
        public void freshCityUi() {
            Log.d("info", String.valueOf(provinceId));
            cityList = DataSupport.where("provinceId=?",
                    String.valueOf(provinceId)).find(City.class);
            Log.d("info", String.valueOf(cityList.size()));
            if (cityList.size() > 0) {
                datalist.clear();
                for (City city : cityList) {
                    datalist.add(city.getCityName());
                }
                arrayAdapter.notifyDataSetChanged();
            }
            temp = 1;
        }

        /**
         * 刷新乡村ui办法
         */
        public void freshCountryUi() {
            Log.d("info", String.valueOf(provinceId + 99 + cityId));
            countyList = DataSupport.where("cityId=?",
                    String.valueOf(cityId)).find(County.class);
            Log.d("info", String.valueOf(countyList.size()));
            if (countyList.size() > 0) {
                datalist.clear();
                for (County county : countyList) {
                    datalist.add(county.getCountyName());
                }
                arrayAdapter.notifyDataSetChanged();
            }
            temp = 2;
        }

        /**
         * 封装http请求获取数据
         *
         * @param address 请求地址
         * @param type    类型
         */
        private void queryDataFromServer(final String address, final String type) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(address).build();
                        client.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                String responseData = response.body().string();
                                Log.d("responseData", responseData);
                                if ("province".equals(type)) {
                                    handleProvinceResponse(responseData);
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            freshProUi();
                                        }
                                    });
                                } else if ("city".equals(type)) {
                                    handleCityResponse(responseData, provinceId);
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            freshCityUi();
                                        }
                                    });
                                } else if ("county".equals(type)) {
                                    handleCountryResponse(responseData, cityId);
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            freshCountryUi();
                                        }
                                    });
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        /**
         * 存储省份数据
         *
         * @param response
         * @return
         */
        static boolean handleProvinceResponse(String response) {
            Log.d("info", "写入省市数据");
            if (!TextUtils.isEmpty(response)) {
                try {
                    DataSupport.deleteAll(Province.class);
                    JSONArray allprovince = new JSONArray(response);
                    for (int i = 0; i < allprovince.length(); i++) {
                        JSONObject provinceObject = allprovince.getJSONObject(i);
                        Province province = new Province();
                        province.setId(provinceObject.getInt("id"));
                        province.setProvinceName(provinceObject.getString("name"));
                        province.setProvinceCode(provinceObject.getInt("id"));
                        province.assignBaseObjId(0);
                        province.save();
                    }
                    return true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        /**
         * 存储城市信息
         *
         * @param response   城市体
         * @param provinceId 省份id
         * @return
         * @throws JSONException
         */
        static boolean handleCityResponse(String response, int provinceId) {
            if (!TextUtils.isEmpty(response)) {
                try {
                    DataSupport.deleteAll(City.class);
                    JSONArray allCity = new JSONArray(response);
                    for (int i = 0; i < allCity.length(); i++) {
                        JSONObject cityObject = allCity.getJSONObject(i);
                        City city = new City();
                        city.setCityCode(cityObject.getInt("id"));
                        city.setCityName(cityObject.getString("name"));
                        city.setProvinceId(provinceId);
                        city.assignBaseObjId(0);
                        city.save();
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        /**
         * 存储县级数据
         *
         * @param responseData
         * @param cityId       城市id
         * @return
         */
        static boolean handleCountryResponse(String responseData, int cityId) {
            Log.d("info", "写入县数据");
            if (!TextUtils.isEmpty(responseData)) {
                try {
                    DataSupport.deleteAll(County.class);
                    JSONArray allCountry = new JSONArray(responseData);
                    for (int i = 0; i < allCountry.length(); i++) {
                        JSONObject countryObject = allCountry.getJSONObject(i);
                        County county = new County();
                        county.setId(countryObject.getInt("id"));
                        county.setCountyName(countryObject.getString("name"));
                        county.setCityId(cityId);
                        county.setWeatherId(countryObject.getString("weather_id"));
                        county.assignBaseObjId(0);
                        county.save();
                    }
                    return true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    }